package com.zfzs.post.modules.goods.service.impl;

import com.zfzs.post.modules.goods.domain.Goods;
import com.zfzs.post.modules.goods.repository.GoodsRepository;
import com.zfzs.post.modules.goods.service.GoodsService;
import com.zfzs.post.modules.goods.service.dto.GoodsCriteria;
import com.zfzs.post.page.JpaPageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
* @author wq
* @date 2019-09-30
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class GoodServiceImpl implements GoodsService {

    @Autowired
    private GoodsRepository goodsRepository;


    @Override
    public List<Goods> findList(Goods goods){
        ExampleMatcher exampleMatcher=ExampleMatcher.matchingAll()
                .withMatcher("channelId",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("isShow",ExampleMatcher.GenericPropertyMatchers.contains());


        if(goods.getGoodsType()!=null && goods.getGoodsType()!=0){
            exampleMatcher.withMatcher("goodsType",ExampleMatcher.GenericPropertyMatchers.contains());
        }

        Example<Goods> ex = Example.of(goods, exampleMatcher);
        List<Goods> goodsList = goodsRepository.findAll(ex);
        return goodsList;
    }

    @Override
    public Goods findById(String id) {
        Optional<Goods> byId = goodsRepository.findById(id);
        return byId.isPresent() ? byId.get() : null;
    }

    @Override
    public List<Goods> findByIds(List<String> ids) {
        return goodsRepository.findByIdIn(ids);
    }

    @Override
    public Page<Goods> queryGoodsPageList(GoodsCriteria criteria, Integer page, Integer size) {
        Goods goods = new Goods();
        goods.setChannelId(criteria.getChannelId());
        goods.setGoodsType(criteria.getGoodsType());
        ExampleMatcher exampleMatcher = ExampleMatcher.matchingAll();
        if (goods.getGoodsType() != null) {
            exampleMatcher.withMatcher("goodsType", ExampleMatcher.GenericPropertyMatchers.contains());
        }
        if(goods.getChannelId() != null){
            exampleMatcher.withMatcher("channelId", ExampleMatcher.GenericPropertyMatchers.contains());
        }
        Example<Goods> ex = Example.of(goods, exampleMatcher);
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");
        Page<Goods> list = goodsRepository.findAll(ex, pageable);
        return list;
    }

    @Override
    public void save(Goods goods) {
        goodsRepository.save(goods);
    }

    @Override
    public void delete(String id) {
        goodsRepository.deleteById(id);
    }

}